package com.tanhua.server.service;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.server.Interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentService {

    @Reference
    private CommentApi commentApi;


    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Reference
    private UserInfoApi userInfoApi;


    @Autowired
    private MovementsMQService movementsMQService;

    private static final String freezingComment = "userFreezing_comment_";


    /**
     * 作用： 点赞
     * @param publishId  动态的id
     * @return
     */
    public ResponseEntity<Object> likeComment(String publishId) {
        //1. 创建一个评论对象，并且补全参数
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId)); //朋友圈的id
        comment.setCommentType(1); //评论类型： 1 点赞 2评论 3喜欢
        comment.setPubType(1); //评论的产品类型： 1 朋友圈  2 。视频  3 评论
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());

        //2. 保存评论的数据 ，返回点赞数量
        int likeCount =  commentApi.save(comment);

        //发送消息到rocketmq
        movementsMQService.likePublishMsg(publishId);

        //3. 做一个你已经对该朋友圈点赞过的标记, 使用redis做标记
        String key ="publish_like_comment_"+UserHolder.getUserId()+"_"+publishId;
        redisTemplate.opsForValue().set(key,"1");  //某用户对某一个朋友圈点赞了

        //4. 返回点赞的数量
        return ResponseEntity.ok(likeCount);
    }

    //取消点赞
    public ResponseEntity<Object> dislikeComment(String publishId) {
        //1. 创建评论对象
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(1);//
        comment.setPubType(1); // 评论的产品类型： 1 朋友圈 2 视频 3 评论
        comment.setUserId(UserHolder.getUserId());
        //2. 删除评论,得到点赞数
       int likeCount =  commentApi.delete(comment);

        //3. 清楚reids已经点赞的标记
        String key ="publish_like_comment_"+UserHolder.getUserId()+"_"+publishId;
        redisTemplate.delete(key);

        //4. 返回响应
        return ResponseEntity.ok(likeCount);

    }

    //喜欢
    public ResponseEntity<Object> loveComment(String publishId) {

        //1. 创建一个评论对象，并且补全参数
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId)); //朋友圈的id
        comment.setCommentType(3); //评论类型： 1 点赞 2评论 3喜欢
        comment.setPubType(1); //评论的产品类型： 1 朋友圈  2 。视频  3 评论
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());

        //2. 保存评论的数据 ，返回喜欢数量
        int loveCount =  commentApi.save(comment);

        //3. 做一个你已经对该朋友圈点赞过的标记, 使用redis做标记
        String key ="publish_love_comment_"+UserHolder.getUserId()+"_"+publishId;
        redisTemplate.opsForValue().set(key,"1");  //某用户对某一个朋友圈点赞了

        //4. 返回点赞的数量
        return ResponseEntity.ok(loveCount);
    }

    //取消喜欢
    public ResponseEntity<Object> unloveComment(String publishId) {

        //1. 创建评论对象
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(3);//
        comment.setPubType(1); // 评论的产品类型： 1 朋友圈 2 视频 3 评论
        comment.setUserId(UserHolder.getUserId());
        //2. 删除评论,得到点赞数
        int loveCount =  commentApi.delete(comment);

        //3. 清楚reids已经点赞的标记
        String key ="publish_love_comment_"+UserHolder.getUserId()+"_"+publishId;
        redisTemplate.delete(key);

        //4. 返回响应
        return ResponseEntity.ok(loveCount);
    }


    /**
     * 查询评论列表
     * @param movementId
     * @param page
     * @param pagesize
     * @return
     */
    public ResponseEntity<Object> queryCommentsList(String movementId, Integer page, Integer pagesize) {

        //1. 根据动态的id查询动态的评论，得到pageResult. PageResult里面存储的是Comment
        PageResult pageResult = commentApi.queryCommentsList(movementId,page,pagesize);

        //得到pageResult的Items
        List<Comment> commentList = (List<Comment>) pageResult.getItems();
        List<CommentVo> voList = new ArrayList<>();
        //2. 把Comment对象转换为CommentVo对象
        if(!commentList.isEmpty()) {
            for (Comment comment : commentList) {
                CommentVo commentVo = new CommentVo();
                commentVo.setId(comment.getId().toString());
                //查找评论人的用户信息
                UserInfo userInfo = userInfoApi.findById(comment.getUserId());
                commentVo.setAvatar(userInfo.getAvatar());
                commentVo.setNickname(userInfo.getNickname());
                commentVo.setContent(comment.getContent());
                commentVo.setCreateDate(new DateTime(comment.getCreated()).toString("yyyy年MM月dd日 HH:mm:ss"));
                commentVo.setLikeCount(0);
                commentVo.setHasLiked(0);
                voList.add(commentVo);
            }
        }
        //3. 修改pageResult存储的内容
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);

    }

    //保存评论
    public ResponseEntity<Object> saveComments(String movementId, String content) {
        long userId = UserHolder.getUserId();

        //判断用户是否被冻结
        Boolean b = redisTemplate.hasKey(freezingComment + userId);
        if(b!=null) {
            if (b) {
                return ResponseEntity.status(500).body(ErrorResult.freezingError());
            }
        }
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId)); //动态的id
        comment.setCommentType(2); //评论的类型： 1点赞  2 评论
        comment.setPubType(1); //产品类型： 1 朋友圈 2 视频  3 评论
        comment.setContent(content);
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());

        commentApi.save(comment);

        return ResponseEntity.ok(null);


    }
}
